# 钉钉机器人推送工具函数
import json
import requests
import hashlib
import hmac
import base64
import time
from urllib.parse import quote_plus
from datetime import datetime
from .dingtalk_config import DINGTALK_WEBHOOK_URL, DINGTALK_SECRET, MESSAGE_TEMPLATES

def generate_sign(secret, timestamp):
    """
    生成钉钉机器人加签
    """
    if not secret:
        return None
        
    string_to_sign = f'{timestamp}\n{secret}'
    hmac_code = hmac.new(
        secret.encode('utf-8'), 
        string_to_sign.encode('utf-8'), 
        digestmod=hashlib.sha256
    ).digest()
    sign = quote_plus(base64.b64encode(hmac_code))
    return sign

def format_work_plan_message(data):
    """
    格式化工作计划消息
    """
    experiment_type = data.get('experiment_type', '其他')
    date = data.get('date', '')
    projects = data.get('projects', [])
    
    # 格式化日期
    try:
        date_obj = datetime.strptime(date, '%Y-%m-%d')
        weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
        weekday = weekdays[date_obj.weekday()]
        formatted_date = f"{date} ({weekday})"
    except:
        formatted_date = date
    
    # 构建消息内容
    title = f"{experiment_type} - {formatted_date}"
    content_lines = [f"## {title}\n"]
    
    if not projects:
        content_lines.append("暂无工作计划安排")
    else:
        # 收集所有值班安排（仅热学试验）
        duty_info = []
        if experiment_type == '热学试验':
            for project in projects:
                duty_day = project.get('duty_day', '')
                duty_night = project.get('duty_night', '')
                if duty_day:
                    duty_info.append(f"日班：{duty_day}")
                if duty_night:
                    duty_info.append(f"夜班：{duty_night}")
        
        # 添加值班安排
        if duty_info:
            content_lines.append("**值班安排：**")
            content_lines.append(" ".join(duty_info))
            content_lines.append("")
        
        # 收集所有工作项，不区分项目
        all_work_items = []
        for project in projects:
            work_items = project.get('work_items', [])
            all_work_items.extend(work_items)
        
        # 添加工作内容
        if all_work_items:
            content_lines.append("**工作内容：**")
            for j, item in enumerate(all_work_items, 1):
                content = item.get('content', '')
                responsible = item.get('responsible', '')
                participants = item.get('participants', '')
                start_time = item.get('start_time', '')
                end_time = item.get('end_time', '')
                
                if content:
                    # 构建完整的工作项信息
                    info_parts = [content]
                    
                    # 时间信息
                    if start_time:
                        try:
                            start_dt = datetime.fromisoformat(start_time.replace('Z', '+00:00'))
                            info_parts.append(f"开始：{start_dt.strftime('%H:%M')}")
                        except:
                            pass
                    if end_time:
                        try:
                            end_dt = datetime.fromisoformat(end_time.replace('Z', '+00:00'))
                            info_parts.append(f"结束：{end_dt.strftime('%H:%M')}")
                        except:
                            pass
                    
                    # 人员信息
                    if responsible:
                        info_parts.append(f"负责：{responsible}")
                    if participants:
                        info_parts.append(f"执行：{participants}")
                    
                    # 输出所有信息，用 | 分隔
                    content_lines.append(f"{j}. {' | '.join(info_parts)}")
        else:
            content_lines.append("暂无具体工作内容")
            content_lines.append("")
    
    # 添加时间戳
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    content_lines.append(f"\n---\n发送时间：{current_time}")
    
    return "\n".join(content_lines)

def send_to_dingtalk(message_content):
    """
    发送消息到钉钉群
    """
    try:
        # 准备请求URL
        url = DINGTALK_WEBHOOK_URL
        
        # 如果配置了密钥，添加签名
        if DINGTALK_SECRET:
            timestamp = str(round(time.time() * 1000))
            sign = generate_sign(DINGTALK_SECRET, timestamp)
            url += f"&timestamp={timestamp}&sign={sign}"
        
        # 准备消息数据
        message_data = {
            "msgtype": "markdown",
            "markdown": {
                "title": "日工作计划安排",
                "text": message_content
            }
        }
        
        # 发送请求
        headers = {'Content-Type': 'application/json'}
        response = requests.post(
            url, 
            data=json.dumps(message_data), 
            headers=headers,
            timeout=10
        )
        
        # 检查响应
        if response.status_code == 200:
            result = response.json()
            if result.get('errcode') == 0:
                return {'success': True, 'message': '发送成功'}
            else:
                return {
                    'success': False, 
                    'message': f"钉钉API错误: {result.get('errmsg', '未知错误')}"
                }
        else:
            return {
                'success': False, 
                'message': f"HTTP错误: {response.status_code}"
            }
            
    except requests.exceptions.Timeout:
        return {'success': False, 'message': '请求超时'}
    except requests.exceptions.RequestException as e:
        return {'success': False, 'message': f'网络请求失败: {str(e)}'}
    except Exception as e:
        return {'success': False, 'message': f'发送失败: {str(e)}'}

def push_work_plan_to_dingtalk(data):
    """
    推送工作计划到钉钉群
    """
    try:
        # 格式化消息
        message_content = format_work_plan_message(data)
        
        # 发送到钉钉
        result = send_to_dingtalk(message_content)
        
        return result
        
    except Exception as e:
        return {'success': False, 'message': f'推送失败: {str(e)}'}